package com.aimee.client;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private EditText etUserName;
    private EditText etUserPassword;

    private HashMap<String, String> stringHashMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        etUserName = findViewById(R.id.et_data_user_name);
        etUserPassword = findViewById(R.id.et_data_user_password);
    }

    public void loginGET(View view) {
        stringHashMap.put("username", etUserName.getText().toString());
        stringHashMap.put("password", etUserPassword.getText().toString());
        new Thread(getRun).start();
    }

    public void loginPOST(View view) {
        stringHashMap.put("username", etUserName.getText().toString());
        stringHashMap.put("password", etUserPassword.getText().toString());
        new Thread(postRun).start();
    }

    Runnable getRun = new Runnable() {
        @Override
        public void run() {
            requestGet(stringHashMap);
        }
    };

    Runnable postRun = new Runnable() {
        @Override
        public void run() {
            requestPost(stringHashMap);
        }
    };

    /**
     * get提交数据
     * @param paramsMap
     */
    private void requestGet(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "http://10.20.1.112:8080/Test2Service/servlet/LoginDateServlet?";
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));
                pos++;
            }
            Log.i(TAG, "params--get-->>" + tempParams.toString());
            String requestUrl = baseUrl + tempParams.toString();

            URL url = new URL(requestUrl); // 新建一个URL对象
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 打开一个HttpURLConnection连接
            urlConn.setConnectTimeout(5 * 1000); // 设置连接主机超时时间
            urlConn.setReadTimeout(5 * 1000); // 设置从主机读取数据超时
            urlConn.setUseCaches(true); // 设置是否使用缓存 默认是true
            urlConn.setRequestMethod("GET"); // 设置为GET请求
            // urlConn设置请求头信息
            urlConn.setRequestProperty("Content-Type", "application/json"); // 设置请求中的媒体踢类型信息
            urlConn.addRequestProperty("Connection", "Keep-Alive"); // 设置客户端与服务端连接类型
            urlConn.connect(); // 开始连接

            if (urlConn.getResponseCode() == 200) { // 判断请求是否成功
                String result = streamToString(urlConn.getInputStream()); // 获取返回的数据
                Log.i(TAG, "GET方式请求成功， result---> " + result);
            } else {
                Log.i(TAG, "GET方式请求失败");
            }
            urlConn.disconnect(); // 关闭连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * post 提交数据
     */
    private void requestPost(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "http://10.20.1.112:8080/Test2Service/servlet/LoginDateServlet";
            // 合并参数
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));
                pos++;
            }
            String params = tempParams.toString();
            Log.i(TAG, "params--post-->> " + params);

            // 请求的参数转换为byte数组
//            byte[] postData = params.getBytes();
            // 新建一个URL对象
            URL url = new URL(baseUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间
            urlConn.setConnectTimeout(5 * 1000);
            // 设置从主机读取数据超时
            urlConn.setConnectTimeout(5 * 1000);
            // Post请求必须设置允许输出 默认false
            urlConn.setDoOutput(true);
            // 设置请求允许输入 默认是true
            urlConn.setDoInput(true);
            // Post请求不能使用缓存
            urlConn.setUseCaches(false);
            // 设置为Post请求
            urlConn.setRequestMethod("POST");
            // 设置本次连接是否自动处理重定向
            urlConn.setInstanceFollowRedirects(true);
            // Post请求不能配置请求Content-Type
//            urlConn.setRequestProperty("Content-Type", "application/json");
            // 开始连接
            urlConn.connect();

            // 发送请求参数
            PrintWriter dos = new PrintWriter(urlConn.getOutputStream());
            dos.write(params);
            dos.flush();
            dos.close();

            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 获取返回的数据
                String result = streamToString(urlConn.getInputStream());
                Log.i(TAG, "Post方式请求成功，result --> " + result);
            } else {
                Log.i(TAG, "Post方式请求失败");
            }

            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将输入流转换成字符串
     * @param is 从网络获取的输入流
     * @return
     */
    private String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
